package com.xu.controller;

import com.xu.pojo.Books;
import com.xu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    @RequestMapping("allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }

    @RequestMapping("toAddBook")
    public String toAddPage(){
        return "addBook";
    }

    @PostMapping("addBook")
    public String addBook(Books book){
        bookService.addBook(book);
        return "redirect:/book/allBook";    //重定向到@RequestMapping("allBook")
    }

    @RequestMapping("toUpdateBook")
    public String toUpdatePage(int id,Model model){
        Books book = bookService.queryBookById(id);
        model.addAttribute("Qbook",book);
        return "updateBook";
    }

    @PostMapping("updateBook")
    public String UpdateBook(Books book){
        bookService.updateBook(book);
        return "redirect:/book/allBook";    //重定向到@RequestMapping("allBook")
    }

    @RequestMapping("deleteBook")
    public String deleteBook(int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";    //重定向到@RequestMapping("allBook")
    }

    @PostMapping("queryBookByName")
    public String queryBookByName(String queryBookName, Model model){
        Books book = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<>();
        //处理查询为空的情况
        if (book==null) {
            list = bookService.queryAllBook();
            model.addAttribute("error","查询为空");
        }
        else {
            list.add(book);
        }
        model.addAttribute("list", list);
        return "allBook";
    }
}
